'use strict';
var  fs = require('fs');
var cache = require('./medecin_cache');
var utils = require('./common_utils');

var NUMBER_OF_RESULTS = 50;

//////////////////////////// MEDECINS

var parseRequest = function (req) 
{
//	console.log(" parseRequest  ");
	if (req && req.body) {
		return req.body;
	}
	return null;
}

// GET

exports.getAllMedecins = function(req,res) {

	console.log("\n\n DEBUG-api: getAllMedecins ")

	try {

//		var medecinIndex = parseRequest(req);
		var inputData = parseRequest(req);
		var filteredList = cache.data.medecins;
		if (filteredList.length > 0) {
			if (inputData) {
				console.log(inputData)
				filteredList = cache.getFilteredMedecinList(inputData.data.split(","));
			}
			filteredList = filteredList.slice(0,NUMBER_OF_RESULTS);
			if(res) res.json(filteredList);
			return;
		}
	
		filteredList = cache.browseAllMedecinFolders().slice(0,NUMBER_OF_RESULTS);
		console.log("getAllMedecins - READ: #" + cache.data.medecins.length+ " medecins");
		
		if(res) res.json(filteredList);
	}
	catch (err) {
		console.log("Error occurred while reading file "+err);
		if(res) res.send(404);
	}
}


/* *
 * Mehtode pour la lecture des medecins dans le file system
 * @params: /:name/:surname/:id
 */
exports.getMedecin = function(req,res) {

	console.log("\n\n DEBUG-api: getMedecin ")

	try {
		var medecinJson = parseRequest(req);
		
		utils.open(utils.MEDECINS_FOLDER, medecinJson.nom, medecinJson.prenom, medecinJson.id, function(status,data){
			if (status == 200) {
				res.json(data);
			}
			else {
				res.send(status);
			}
		});
	}
	catch (err) {
		console.log("Error occurred while reading file "+err);
		res.send(404);
	}
}


// POSTS
exports.updateMedecin = function(req,res) {

	console.log("\n\n DEBUG-api: updateMedecin ")
	
	try {
		var medecinJson = parseRequest(req);
		var medecinIndex = cache.getJsonIndexForMedecin(medecinJson.nom, medecinJson.prenom, medecinJson.id);
		
		utils.save(medecinJson,utils.MEDECINS_FOLDER,medecinJson.nom, medecinJson.prenom, medecinJson.id,function(status){
			if (status==200) {
				cache.updateMedecin(medecinIndex);
				res.json(medecinIndex);
			}
			else {
				res.send(status);
			}
		});

	}
	catch (err) {
		console.log("Error occurred while saving file "+err);
		res.send(404);
	}
}

//DELETE
exports.deleteMedecin = function(req,res) {

	console.log("\n\n DEBUG-api: deleteMedecin ");

	try {
		var medecinIndex = parseRequest(req);
		utils.delete(medecinIndex.path,function(status) {
			if (status == 200) {
				res.send(cache.removeMedecin(medecinIndex)?200:404);
			}
			else {
				console.log(medecinIndex.path+" cannot be removed");
				res.send(404);
			}
		});
		
	}
	catch (err) {
		console.log("Error occurred while removing file "+err);
		res.send(404);
	}
}